package com.mychoize.app.cricscore;

import javax.persistence.EntityManager;

import com.google.appengine.api.datastore.KeyFactory;

public class SimpleScoreService {
	
/*	public SimpleScore getScoreById(final int id){
		if(id <= 0){
			return null;
		}
		EntityManager em = null;
		SimpleScore score = null;
		try{
			em = EMF.get().createEntityManager();
			score = em.find(SimpleScore.class, id);
		}catch(Exception e){
		}finally{
			if(em!=null){
				em.close();
			}
		}
		return score;
	}
*/	
	public void insertOrUpdateScore(final SimpleScore score){
		if(score == null){
			//System.out.println("score is null");
			return;
		}
		EntityManager em = null;
		SimpleScore simpleScore = null;
		
		try{
			em = EMF.get().createEntityManager();
//			Query q = em.createQuery("SELECT s FROM SimpleScore s WHERE s.id = :id"); 
//			q.setParameter("id",score.getId()); 
//			simpleScore = (SimpleScore) q.getSingleResult();
			simpleScore = em.find(SimpleScore.class, KeyFactory.createKey(SimpleScore.class.getSimpleName(), score.getId()));
			if(simpleScore == null){
				em.persist(score);
				//System.out.println("inserting record");
			}else if(!simpleScore.getSimple().equals(score.getSimple()) ||
						!simpleScore.getDetail().equals(score.getDetail())){
				score.setVersion(simpleScore.getVersion()+1);
				em.merge(score);
				//System.out.println("updating record");
			}
		}catch(Exception e){
			e.printStackTrace();
		}finally{
			if(em!=null){
				em.close();
			}
		}
		System.out.println("version: " + score.getVersion());
	}
	
}
